package cutCriteria;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import neural.Individual;
import core.Problem;

public class ContentCutCriteria implements CutCriteria {

	private Double previousMax;
	private double delta;
	private int gencounter=0;

	public ContentCutCriteria(double delta) {
		this.delta = 0.0001;
	}

	@Override
	public Boolean shouldFinish(Problem problem) {

		double b = getMax(problem.getIndividuals());
		if (previousMax == null) {
			previousMax = b;
			return false;
		}
		if (Math.abs(b - previousMax) > delta) {
			previousMax = Math.max(b, previousMax);
			gencounter = 0;
		}else{
			gencounter++;
		}

		return gencounter > 10;
	}

	private double getMax(List<Individual> individuals) {
		List<Double> aptitudes = new ArrayList<Double>();

		for (Individual d : individuals) {
			aptitudes.add(d.getFitness());
		}

		Collections.sort(aptitudes, new Comparator<Double>() {

			@Override
			public int compare(Double o1, Double o2) {

				return (int) Math.ceil(o2 - o1);
			}

		});

		return aptitudes.get(0);

	}
}
